package com.armed.ejb.sessions;

import com.armed.ejb.transference.Medico;
import com.armed.ejb.transference.helpers.DataReverseTransferHelper;
import com.armed.ejb.transference.helpers.DataTransferHelper;
import com.armed.excepciones.medicos.MedicoAsociadoAVentaException;
import com.armed.excepciones.personas.PersonaRepetidaException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;
import javax.ejb.Stateless;
import javax.naming.NamingException;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;

/**
 * Class MedicosFacade
 *
 *
 * @author init() software
 * @version 24/02/2008 
 */
@Stateless
public class MedicosFacade implements MedicosFacadeRemote 
{
    @PersistenceContext
    private EntityManager em;
    /** Constructor of MedicosFacade */
    public MedicosFacade()
    {
    }

    public void create(Medico medicos) throws PersonaRepetidaException
    {
        try
        {
            em.persist(DataReverseTransferHelper.revertDoctor(medicos));
            em.flush();
        }
        catch (PersistenceException e)
        {
            if (e.getCause().getCause() instanceof SQLIntegrityConstraintViolationException)
                throw new PersonaRepetidaException(medicos);
            else
                throw e;
        }
    }

    public void edit(Medico medicos) throws PersonaRepetidaException
    {
        try
        {
            em.merge(DataReverseTransferHelper.revertDoctor(medicos));
            em.flush();
        }
        catch (PersistenceException e)
        {
            if (e.getCause().getCause() instanceof SQLIntegrityConstraintViolationException)
                throw new PersonaRepetidaException(medicos);
            else
                throw e;
        }
    }

    public void remove(Medico medicos) throws MedicoAsociadoAVentaException
    {
        try
        {
            em.remove(em.merge(DataReverseTransferHelper.revertDoctor(medicos)));
            em.flush();
        }
        catch (PersistenceException e)
        {
            if (e.getCause().getCause() instanceof SQLIntegrityConstraintViolationException)
                throw new MedicoAsociadoAVentaException(medicos);
            else
                throw e;
        }
    }

    public Medico find(Object id)
    {
        return DataTransferHelper.copyDoctor(em.find(com.armed.ejb.entities.Medicos.class, id));
    }

    public List<Medico> findAll()
    {
        return DataTransferHelper.copyDoctorsToList(em.createQuery("select object(o) from Medicos as o").getResultList());
    }
}
